//
//  MTCContractAuditViewController.m
//  ERP
//
//  Created by QA on 16/3/30.
//  Copyright © 2016年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "MTCContractAuditViewController.h"

#import "MJRefresh.h"
#import "MTContractListViewCell.h"
#import "UITableView+Custom.h"
#import "NSKeyedArchiverUserLogin.h"

#import "NSDictionary+DataFormat.h"
#import "WebServiceCommonRequest.h"

#import "MTCContractDetailViewController.h"
#import "MTCSearchContractViewController.h"

@interface MTCContractAuditViewController ()

@property (strong, nonatomic) NSMutableArray *resultData;
@property (assign, nonatomic) NSInteger segmentActionState;

@end

@implementation MTCContractAuditViewController
@synthesize segmentedView = _segmentedView;
@synthesize tableView = _tableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setTitle: @"合同审核"];
        UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"搜索" style:UIBarButtonItemStyleDone target:self
                                                                      action:@selector(searchContractSelector:)];
        self.navigationItem.rightBarButtonItem = leftButton;
        
        //设置搜索按钮
        UIButton* righButtont= [UIButton buttonWithType:UIButtonTypeCustom];
        righButtont.frame = CGRectMake(0, 0, 44, 44);
        [righButtont setImage:[UIImage imageNamed:@"home_nav_left_serch"] forState:UIControlStateNormal];
        //[righButtont setImage:[UIImage imageNamed:@"home_nav_left_serch_e"] forState:UIControlStateHighlighted];
        [righButtont addTarget:self action:@selector(searchContractSelector:) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:righButtont];
        
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.resultData = [NSMutableArray array];
    self.tableView.tableFooterView= [[UIView alloc] init];
    
    [self.segmentedView setTintColor:ThemeColorBlue];
    [self.segmentedView addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    [self setupRefresh];
}

- (void)setupRefresh
{
    //添加下拉加载数据
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    [self.tableView headerBeginRefreshing];
    [self.tableView footerEndRefreshing];
}

- (void)stopRefresh
{
    //移除下拉加载数据
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
}

//具体委托方法实例
-(void)segmentAction:(UISegmentedControl *)Seg
{
    NSInteger index = Seg.selectedSegmentIndex;
    self.segmentActionState = index;
    
    [self.resultData removeAllObjects];
    [self.tableView reloadData];
    [self.tableView headerBeginRefreshing];
}


#pragma mark 网络获取数据

- (void)getNetWorkDataIsReresh:(BOOL)isReresh state:(NSNumber*)state end:(NSNumber*)end
{
    //@状态（全部、供毕、正供、待供）
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"HTGL_HTLB_LIST_20170117"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    [content addParameterKey:@"起始条数" value:state];
    [content addParameterKey:@"结束条数" value:end];
    [content addParameterKey:@"合同性质" value:@""];//--1:正式合同;2:临时合同;3:现金合同;
    [content addParameterKey:@"审核状态" value:_segmentActionState == 0 ? @"1" : @""];//--1:未审核;2:已审核
    [content addParameterKey:@"合同状态" value:_segmentActionState == 1 ? @"1" : @""];//--1:待授权;2:已授权;3:已终止
    [content addParameterKey:@"分发状态" value:_segmentActionState == 2 ? @"0" : @""];//--0:未分发;1:已分发
    [content addParameterKey:@"客户编号" value:@""];
    [content addParameterKey:@"检索条件" value:@""];
    [content addParameterKey:@"合同ID" value:@""];
    
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    [content addParameterKey:@"用户ID" value:userInfo.Id];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if(isReresh) [self.tableView headerEndRefreshing];
        else [self.tableView footerEndRefreshing];
        
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        if(isReresh) [self.resultData removeAllObjects];
        if(firstArray && firstArray.count>0){
            [self.resultData addObjectsFromArray:firstArray];
            [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
            [self.tableView reloadData];
        } else if(isReresh){
            [self.tableView setTableViewNotDataDrawText:@"暂无合同" isShow:YES];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        if(isReresh)[self errorInfoViewText:@"哦，出错了"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        if(isReresh)[self errorInfoViewText:@"无法连接网络"];
    }];
    
}

- (void)errorInfoViewText:(NSString*)label
{
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
    
    if (self.tableView.visibleCells.count <= 0) {
        [self.tableView setTableViewNotDataDrawText:label isShow:YES];
    } else {
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        [self showErrorHUDText:label];
    }
}

#pragma mark 开始进入刷新状态

- (void)headerRereshing
{
    NSNumber *stateNumber = [NSNumber numberWithInteger:0];
    NSNumber *endNumber = [NSNumber numberWithInteger:10];
    [self getNetWorkDataIsReresh:YES state:stateNumber end:endNumber];
}

- (void)footerRereshing
{
    NSNumber *stateNumber = [NSNumber numberWithInteger:self.resultData.count + 1];
    NSNumber *endNumber = [NSNumber numberWithInteger:self.resultData.count + 10];
    [self getNetWorkDataIsReresh:NO state:stateNumber end:endNumber];
}

#pragma mark - Table view data source

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        return @"";
    } else {
        return @" 消息搜索结果";
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.resultData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifierOne = @"MTContractListViewCell";
    MTContractListViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifierOne];
    if (!cell)
        cell = [[MTContractListViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifierOne];
    
    NSDictionary *model = [self.resultData objectAtIndex:indexPath.row];
    cell.HTBHLabel.text = [model objectFormatStringForKey:@"合同编号" defaults:@"未知"];
    cell.HTMCLabel.text = [model objectFormatStringForKey:@"合同名称" defaults:@"未知"];
    cell.HTXZLabel.text = [model objectFormatStringForKey:@"合同性质" defaults:@"未知"];
    cell.LJFLLabel.text = [model objectFormatStringForKey:@"合同总量" format:@"累计%@方" defaults:@"未知"];
    
    if(self.segmentActionState == 0){
        cell.HTJDLabel.text = [model objectFormatStringForKey:@"审核状态" defaults:@"未知"];
        cell.threeLabel.text = [model objectFormatStringForKey:@"审核人员" defaults:@"未知"];
        cell.fourLabel.text = [model objectFormatStringForKey:@"审核日期" defaults:@"未知"];
        cell.rightFourLabel.text = [model objectFormatStringForKey:@"合同状态" defaults:@"未知"];
        cell.threeNameLabel.text = @"审核人员：";
        cell.fourNameLabel.text = @"审核日期：";
        
    } else if(self.segmentActionState == 2){
        cell.HTJDLabel.text = [model objectFormatStringForKey:@"分发状态" defaults:@"未知"];
        cell.threeLabel.text = [model objectFormatStringForKey:@"业务人员" defaults:@"未知"];
        cell.fourLabel.text = [model objectFormatStringForKey:@"签订日期" defaults:@"未知"];
        cell.rightFourLabel.text = [model objectFormatStringForKey:@"合同状态" defaults:@"未知"];
        
    } else if(self.segmentActionState == 1){
        cell.HTJDLabel.text = [model objectFormatStringForKey:@"合同状态" defaults:@"未知"];
        cell.threeLabel.text = [model objectFormatStringForKey:@"修改人" defaults:@"未知"];
        cell.fourLabel.text = [model objectFormatStringForKey:@"修改日期" defaults:@"未知"];
        cell.rightFourLabel.text = [model objectFormatStringForKey:@"审核状态" defaults:@"未知"];
        cell.threeNameLabel.text = @"修改人员：";
        cell.fourNameLabel.text = @"授权日期：";
        
    } else {
        //cell.HTJDLabel.text = [model objectFormatStringForKey:@"完成进度" format:@"%@%%" defaults:@"未知"];
        cell.HTJDLabel.text = [model objectFormatFloatStringForKey:@"完成进度" retain:1 format:@"%@%%"];
        cell.threeLabel.text = [model objectFormatStringForKey:@"业务人员" defaults:@"未知"];
        cell.fourLabel.text = [model objectFormatStringForKey:@"签订日期" defaults:@"未知"];
        cell.rightFourLabel.text = [model objectFormatStringForKey:@"合同状态" defaults:@"未知"];
    }
    
    return cell;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 82;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *model = [self.resultData objectAtIndex:indexPath.row];
    
    MTCContractDetailViewController *viewController = [[MTCContractDetailViewController alloc] initWithModel:model];
    viewController.backResultDelagate = self;
    [self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark -
#pragma mark BackResultDataDelagate

- (void) backResultDataKey:(id)key dataValue:(id)backValue
{
    //删除合同
    if (key && backValue && [key isEqualToString:@"Delete"]) {
        [self.resultData removeObject:backValue];
        [self.tableView reloadData];
        
        if (self.resultData.count <= 0)
            [self.tableView setTableViewNotDataDrawText:@"暂无合同" isShow:YES];
        
    } else if([key isEqualToString:@"Check"]){
        //合同审核
        NSArray *originalArray = backValue;
        if (!originalArray[1]) return;
        
        NSInteger index = [self.resultData indexOfObject:originalArray[0]];
        if(index > self.resultData.count){
            [self.resultData insertObject:originalArray[1] atIndex:0];
        } else {
            [self.resultData removeObjectAtIndex:index];
            [self.resultData insertObject:originalArray[1] atIndex:index];
        }
        [self.tableView reloadData];
        if (self.resultData.count <= 0)
            [self.tableView setTableViewNotDataDrawText:@"暂无合同" isShow:YES];
        
    } else if([key isEqualToString:@"Modif"]){
        //合同修改
        NSArray *originalArray = backValue;
        if (!originalArray[1]) return;
        
        NSInteger index = [self.resultData indexOfObject:originalArray[0]];
        if(index > self.resultData.count){
            [self.resultData insertObject:originalArray[1] atIndex:0];
        } else {
            [self.resultData removeObjectAtIndex:index];
            [self.resultData insertObject:originalArray[1] atIndex:index];
        }
        [self.tableView reloadData];
        if (self.resultData.count <= 0)
            [self.tableView setTableViewNotDataDrawText:@"暂无合同" isShow:YES];
        
    } else if([key isEqualToString:@"AuthContract"]){
        //合同授权
        NSArray *originalArray = backValue;
        if (!originalArray[1]) return;
        
        if(self.segmentActionState == 2){
            [self.resultData removeObject:originalArray[0]];
        } else {
            NSInteger index = [self.resultData indexOfObject:originalArray[0]];
            if(index > self.resultData.count){
                [self.resultData insertObject:originalArray[1] atIndex:0];
            } else {
                [self.resultData removeObjectAtIndex:index];
                [self.resultData insertObject:originalArray[1] atIndex:index];
            }
        }
        
        [self.tableView reloadData];
        if (self.resultData.count <= 0)
            [self.tableView setTableViewNotDataDrawText:@"暂无合同" isShow:YES];
        
    } else if([key isEqualToString:@"StopContract"]){
        //合同终止
        NSArray *originalArray = backValue;
        if (!originalArray[1]) return;
        
        if(self.segmentActionState == 1){
            [self.resultData removeObject:originalArray[0]];
        } else {
            NSInteger index = [self.resultData indexOfObject:originalArray[0]];
            if(index > self.resultData.count){
                [self.resultData insertObject:originalArray[1] atIndex:0];
            } else {
                [self.resultData removeObjectAtIndex:index];
                [self.resultData insertObject:originalArray[1] atIndex:index];
            }
        }
        
        [self.tableView reloadData];
        if (self.resultData.count <= 0)
            [self.tableView setTableViewNotDataDrawText:@"暂无合同" isShow:YES];
        
    } else if([key isEqualToString:@"Distribute"]){
        //合同分发
        NSArray *originalArray = backValue;
        if (!originalArray[1]) return;
        
        NSInteger index = [self.resultData indexOfObject:originalArray[0]];
        if(index > self.resultData.count){
            [self.resultData insertObject:originalArray[1] atIndex:0];
        } else {
            [self.resultData removeObjectAtIndex:index];
            [self.resultData insertObject:originalArray[1] atIndex:index];
        }
        [self.tableView reloadData];
        if (self.resultData.count <= 0)
            [self.tableView setTableViewNotDataDrawText:@"暂无合同" isShow:YES];
    }
    
}


#pragma mark
#pragma mark IBAction

- (void)searchContractSelector:(id)selector
{
    MTCSearchContractViewController *view = [[MTCSearchContractViewController alloc] init];
    AbstractNavigationController *mNavigation = [[AbstractNavigationController alloc] initWithRootViewController:view];
    [self.navigationController presentViewController:mNavigation animated:YES completion:^{}];
}

@end
